<?php

namespace Portal\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpFoundation\Request;


use Portal\UserBundle\Entity\User;
use Portal\UserBundle\Form\UserType;
use Portal\UserBundle\Form\UserRegisterType;
use Portal\MainBundle\Utils\customFunctions;

class LoginController extends Controller
{

  public function loginAction()
  {

    if ($this->get('request')->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
      $error = $this->get('request')->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
    } else {
      $error = $this->get('request')->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
    }


    $lastEmail = $this->get('request')->getSession()->get(SecurityContext::LAST_USERNAME);
    if (!$lastEmail) {
      $lastEmail = null;
      $this->get('request')->getSession()->set(SecurityContext::LAST_USERNAME, null);
    }
    $entity = new User();
    $form = $this->createForm(new UserType(), $entity);

    return $this->render('PortalUserBundle:Login:login.html.twig', array(
                'last_email' => $lastEmail,
                'error' => $error,
                'form' => $form->createView(),
            ));
  }

  public function loginCheckAction(Request $request)
  {
    $entity = new User();    
    $form = $this->createForm(new UserType(), $entity);
    $form->bind($request);
    
    if ($form->isValid()) {

      $email = customFunctions::filterForLogin($form->getData()->getEmail());
      $password = customFunctions::filterForLogin($form->getData()->getPassword());
      
      if (strlen($email) > 0 && strlen($password) > 0) {
        $user = $this->getDoctrine()->getManager()->getRepository('PortalUserBundle:User')->loginCheck($password, $email, $this->container->getParameter('statusActive'));        
        
        if ($user === FALSE) {
          $this->get('request')->getSession()->set(SecurityContext::LAST_USERNAME, $email);
          $this->get('session')->setFlash('error', $email . ' ' . $this->container->getParameter('loginFail'));
          return new RedirectResponse($this->generateUrl('userLogin'));
        }
        
        
        $this->loginUser($user);        
        $this->get('session')->setFlash('notice', $this->container->getParameter('loginSucess') . ' ' . $user->getFirstName());
        return $this->redirect($this->generateUrl('homepage'));
      }
    }

    $this->get('request')->getSession()->set(SecurityContext::LAST_USERNAME, $email);
    $this->get('session')->setFlash('error', $email . ' ' . $this->container->getParameter('loginFail'));
    return new RedirectResponse($this->generateUrl('userLogin'));
  }

  public function registerAction()
  {
    $error = null;
    $entity = new User();
    
    // Get location array for form
    $locationArray = $this->getDoctrine()->getManager()->getRepository('PortalUserBundle:Location')->getLocationArrayForSelect($this->container->getParameter('statusActive'));
    
    $form = $this->createForm(new UserRegisterType($locationArray), $entity);

    return $this->render('PortalUserBundle:Register:register.html.twig', array(
                'error' => $error,
                'entity' => $entity,
                'form' => $form->createView()
            ));
  }

  public function createUserAction(Request $request)
  {
    $entity = new User();
    // Get location array for form
    $locationArray = $this->getDoctrine()->getManager()->getRepository('PortalUserBundle:Location')->getLocationArrayForSelect($this->container->getParameter('statusActive'));
    $form = $this->createForm(new UserRegisterType($locationArray), $entity);
    $form->bind($request);

    
    if($_POST['portal_userbundle_userregistertype']['email'] != $_POST['email2'])
    {
        $this->get('session')->setFlash('error', 'Уучлаарай и-мэйл хоорондоо таарахгүй байна.');
        return new RedirectResponse($request->headers->get('referer'));
    }
    
    if($_POST['portal_userbundle_userregistertype']['password'] != $_POST['password2'])
    {
        $this->get('session')->setFlash('error', 'Уучлаарай нууц үгүүд хоорондоо таарахгүй байна.');
        return new RedirectResponse($request->headers->get('referer'));
    }
    
    if ($form->isValid()) {
      
      $emailResult = $this->getDoctrine()->getManager()->getRepository('PortalUserBundle:User')->getUserByEmail($entity->getEmail());
      if ($emailResult == FALSE) {
        
        // SET SOME OTHER DATA
        $entity->setPassword($this->generatePassword($entity->getEmail(), $entity->getPassword()));
        $entity->setLastIp($_SERVER['REMOTE_ADDR']);
        $entity->setRoles(array($this->container->getParameter('ROLE_USER')));
        $entity->setCreatedAt(new \DateTime());
        $entity->setIsActive($this->container->getParameter('statusActive'));
//        var_dump($entity->getLocation());die;        
        // SAVE
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        //REDIRECT
        $this->get('session')->setFlash('notice', $this->container->getParameter('successRegister'));
        return $this->redirect($this->generateUrl('userLogin'));
      } else {
        
        // Ийм и-мэйлтэй хэрэглэгч бүртгэгдсэн байна.
        $this->get('session')->setFlash('error', $entity->getEmail() . $this->container->getParameter('registerFail'));
        return $this->redirect($this->generateUrl('userLogin'));
      }
    }else{
        // 
        $this->get('session')->setFlash('error', 'Уучлаарай форм - г зөв бөглөнө үү');
        return $this->redirect($this->generateUrl('userLogin'));
    }
  }

  protected function generatePassword($email, $planPassword)
  {
    $hashedPassword = hash('sha512', $planPassword . $email);
    return $hashedPassword;
  }

  public function logoutAction()
  {
    $this->get('security.context')->setToken(null);
    $this->get('request')->getSession()->invalidate();

    return $this->redirect($this->generateUrl('homepage'));
  }

  protected function loginUser($user)
  {
    $this->container->get('security.context')->setToken(null);
    $token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());
    $this->container->get('security.context')->setToken($token);
    
  }
  
  /**
   * Check user is logged in
   * 
   * @param type $this->container->get('security.context')
   * @return type
   */
  public static function checkUser($securityContext)
  {
    $user = $securityContext->getToken()->getUser();

    if ($user) {
      if (!is_object($user)) {
        header('Location: /logout');
        die;
      }

      if (is_array($user->getRoles()) == FALSE) {
        header('Location: /logout');
        die;
      }

      return $user;
    } else {
      header('Location: /logout');
      die;
    }
  }
  
}
